package site.ycsyxt.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

/**
 * Excel操作相关工具类
 *
 * @author ycs(15241496739 @ 163.com)
 * @date 2022/1/3
 **/
public class ExcelUtils {
    /**
     * 将 Excel 文件流解析成二维行列 List
     *
     * @param inputStream 输入流
     * @return
     */
    public static List<List<String>> parseToContent(InputStream inputStream) {
        List<List<String>> result = new ArrayList<>();
        EasyExcel.read(inputStream, new ContentListener(result)).sheet().doRead();
        return result;
    }

    /**
     * 将 Excel 文件流解析成 List 对象
     *
     * @param inputStream 输入流
     * @param <T>         泛型，使用时传具体对象
     * @param type        具体对象.class
     * @return
     */
    public static <T> List<T> parseToObject(InputStream inputStream, Class<T> type) {
        List<T> result = new ArrayList<>();
        EasyExcel.read(inputStream, type, new ObjectListener(result)).sheet().doRead();
        return result;
    }

    /**
     * 将对象List 写到 Excel 输出流
     *
     * @param type         对象
     * @param data         对象List
     * @param outputStream 输出流
     * @param <T>
     */
    public static <T> void objectToExcel(Class<?> type, List<T> data, OutputStream outputStream) {
        EasyExcel.write(outputStream, type).sheet().doWrite(data);
    }

    /**
     * 将二维List 写到 Excel 输出流
     *
     * @param head         Excel头
     * @param data         内容
     * @param outputStream 输出流
     */
    public static void contentToExcel(List<List<String>> head, List<List<Object>> data, OutputStream outputStream) {
        EasyExcel.write(outputStream).head(head).sheet().doWrite(data);
    }
}

class ObjectListener<T> extends AnalysisEventListener<T> {

    private final List<T> result;

    public ObjectListener(List<T> result) {
        this.result = result;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        result.add(t);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}

class ContentListener extends AnalysisEventListener<Map<Integer, String>> {
    private final List<List<String>> result;

    public ContentListener(List<List<String>> result) {
        this.result = result;
    }

    @Override
    public void invoke(Map<Integer, String> rowMap, AnalysisContext analysisContext) {
        Set<Integer> colIndexSet = rowMap.keySet();
        List<String> rowList = new ArrayList<>();
        for (int colIndex : colIndexSet) {
            rowList.add(rowMap.get(colIndex));
        }
        result.add(rowList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}

